<?php

namespace app\controller;

use app\facade\Token;
use app\model\Users;

class UserController
{
    protected $middleware = [
        'AuthCheck' => [
            'only' => ['refreshToken']
        ],
    ];

    //登录
    public function login()
    {
        $userinfo = request()->only(['username', 'password']);
        $userinfo['password'] = md5($userinfo['password']);
        $user = Users::getByUsername($userinfo['username']);
        if (!$user) {
            return rejson(0, null, '用户名不正确', 201);
        }
        if ($user->password == $userinfo['password']) {
            $token = Token::getToken($user->id);
            $user->token = $token;
            return rejson(1, ['user' => $user], '登陆成功');
        } else {
            return rejson(0, null, '密码错误', 201);
        }
    }

    //注册
    public function register()
    {
        $userinfo = request()->only(['username', 'password']);
        $userinfo['password'] = md5($userinfo['password']);
        $searchUser = Users::getByUsername($userinfo['username']);
        if ($searchUser) {
            return rejson(0, null, '用户名已注册', 500);
        }
        $user = Users::create($userinfo);
        if ($user) {
            return rejson(1, null, '注册成功');
        } else {
            return rejson(0, null, '注册失败', 500);
        }
    }

    //刷新token
    public function refreshToken()
    {
        $token = request()->header('Authorization');
        $res = Token::getTokenData($token);
        if (!$res) {
            return rejson(0, null, '登录已过期，请重新登录', 401);
        }
        $refreshToken = Token::getToken($res->uid);
        return rejson(1, ['token' => $refreshToken]);
    }
}
